<template>
  <a-modal
    title="编辑产品表"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="产品编码"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-input
                readOnly
                placeholder="请输入产品编码"
                v-decorator="['code', {rules: [{required: true, message: '请输入产品编码！'}]}]"/>
            </a-form-item>
            <a-form-item v-show="false">
              <a-input v-decorator="['id']"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="产品名称"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-input
                placeholder="请输入产品名称"
                v-decorator="['name', {rules: [{required: true, message: '请输入产品名称！'}]}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="产品类型"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-tree-select
                v-decorator="['proTypeId', {rules: [{ required: true, message: '请选择产品类型！' }]}]"
                style="width: 100%"
                :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                :treeData="proTree"
                placeholder="请选择产品类型"
              >
                <span slot="title" slot-scope="{ id }">{{ id }}</span>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="工艺路线"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback>
              <a-select
                placeholder="请选择工艺路线"
                v-decorator="['workRouteId',{rules: [{ required: false, message: '请选择工艺路线！'}]}]">
                <a-select-option
                  v-for="(item,index) in workRouteList"
                  :key="index"
                  :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="库存单位"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback>
              <a-select
                placeholder="请选择库存单位"
                v-decorator="['unit',{rules: [{ required: false, message: '请选择库存类型！'}]}]">
                <a-select-option
                  v-for="(item,index) in unit"
                  :key="index"
                  :value="item.code">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item v-if="jsonEditShow">
          <json-edit
            ref="jsonEdit"
            :fieldProp="fieldProp"
          />
        </a-form-item>
        <custom-upload
          ref="image"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :isDisabled="false"
          :isMultiple="false"
          :accept="`image/*`"
          labelName="图片"
          colName="image"
        />
        <a-form-item
          label="备注"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-textarea placeholder="请输入备注" v-decorator="['remarks']" :auto-size="{minRows:3,maxRows:6}"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { proEdit } from '@/api/modular/main/pro/proManage'
import { getProTree } from '@/api/modular/main/protype/proTypeManage'
import XEUtils from 'xe-utils'
import JsonEdit from '@/components/MyComp/JsonEdit'
import { fieldConfigList } from '@/api/modular/main/fieldconfig/fieldConfigManage'
import TagSelectOption from '@/components/TagSelect/TagSelectOption'
import { workRouteList } from '@/api/modular/main/workroute/workRouteManage'
import CustomUpload from '@/views/main/pro/CustomUpload'

export default {
  components: {
    TagSelectOption,
    JsonEdit,
    CustomUpload
  },
  // created() {
  //   if (this.hasPerm('fieldConfig:list')) {
  //     fieldConfigList({ tableName: 'dw_pro' }).then(res => {
  //       res.data.forEach(item => {
  //         // 查询自定义字段
  //         this.fieldProp[item.fieldIndex] = {
  //           type: item.fieldType,
  //           title: item.fieldTitle,
  //           'x-decorator': 'FormItem',
  //           'x-component': 'Input',
  //           'x-component-props': {
  //             placeholder: '请输入',
  //             style: {
  //               width: '100%'
  //             }
  //           }
  //         }
  //       })
  //     })
  //   }
  // },
  data() {
    return {
      fieldProp: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      labelCol_T: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol_T: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      proTree: [],
      unit: [],
      contextImage: '',
      jsonEditShow: true,
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      proTypeIdData: [],
      workRouteList: []
    }
  },
  methods: {
    // 初始化方法
    edit(record) {
      this.visible = true
      workRouteList().then(
        (r) => {
          this.workRouteList = r.data
        }
      )

      this.getProTree()
      // this.text = JSON.parse(record.josn)
      this.dynamicFieldConfig(record.json)
      this.unit = this.$options.filters['dictData']('unit')
      setTimeout(() => {
        this.form.setFieldsValue(
          {
            code: record.code,
            id: record.id,
            image: record.image,
            name: record.name,
            proTypeId: record.proTypeId,
            remarks: record.remarks,
            unit: record.unit,
            workRouteId: record.workRouteId
          }
        )
        this.$refs.image.setFileList(record.image)
        this.$refs.jsonEdit.getEditForm().setValues(JSON.parse(record.josn))
      }, 500)
    },
    // 动态字段赋值
    dynamicFieldConfig(json) {
      this.jsonEditShow = false
      this.fieldProp = {}
      fieldConfigList({ tableName: 'dw_pro' }).then(res => {
        res.data.forEach(item => {
          // 查询自定义字段
          this.fieldProp[item.fieldIndex] = {
            type: item.fieldType,
            title: item.fieldTitle,
            'x-decorator': 'FormItem',
            // 'x-component': 'a-input',
            'x-decorator-props': {
              labelCol: 6,
              // labelWrap: true,
              wrapperCol: 16
            },
            'x-component-props': {
              placeholder: '请输入',
              style: {
                width: '100%'
              }
            }
          }
        })
        this.jsonEditShow = true
      })
    },
    /**
     * 获取类型树，并加载于表单中
     */
    getProTree() {
      getProTree().then((res) => {
        this.formLoading = false
        if (!res.success) {
          this.proTree = []
          return
        }
        this.proTree = res.data
      })
    },
    handleSubmit() {
      this.form.setFieldsValue({
        image: this.$refs.image.getFileList() + this.contextImage
      })
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          values.name = XEUtils.trim(values.name)
          values.code = XEUtils.trim(values.code)
          // values.remark = XEUtils.trim(values.remark)
          values.unit = XEUtils.trim(values.unit)
          for (const key in values) {
            if (typeof (values[key]) === 'object' && values[key] != null) {
              values[key] = JSON.stringify(values[key])
            }
          }
          this.$refs.jsonEdit.getEditForm().submit((josn) => {
            values.josn = josn
            values.isGeneratePieceNo = 1
            values.isGenerateReference = 1
            proEdit(values).then((res) => {
              if (res.success) {
                this.$message.success('编辑成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.message)//  + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      if (this.jsonEditShow) {
        this.$refs.jsonEdit.getEditForm().reset()
      }
      this.$refs.image.setFileList(null)
      this.form.resetFields()
      this.contextImage = ''
      this.visible = false
    }
  }
}
</script>
